import { ref, watch } from 'vue'
import restDataMain from '@/utils/response'
import { ElNotification, ElMessageBox, ElMessage, ElLoading } from 'element-plus'

function randomString(len) {
    len = len || 32
    var $chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'
    var maxPos = $chars.length
    var pwd = ''
    for (let i = 0; i < len; i++) {
        //0~32的整数
        pwd += $chars.charAt(Math.floor(Math.random() * (maxPos + 1)))
    }
    return pwd
}

function service(requestData) {

    return new Promise((resolve, reject) => {
        let loadingInstance = null
        if(!/downFile/.test(requestData.url)){
            loadingInstance = ElLoading.service({ fullscreen: true })
        }
        //设置超时时间
        setTimeout(()=>{
          console.log('超时',loadingInstance)
          if(loadingInstance){
              loadingInstance.close()
          }
        },9000)
        let randomStr = randomString()
        const data = {
            requestUrl: requestData.url,
            requestMethod: 'POST',
            headers: {
                contentType: 'application/json',
            },
            requestBody: {
                subTaskId: '',
                requestId: randomStr,
                ...requestData.data,
            },
            webInfo: {
                requestId: randomStr,
            },
        }
        //windows系统vue应用向主程序发送信息
        if (window.chrome && window.chrome.webview) {
            console.log('向主程序发送了', data)
            window.chrome.webview.postMessage({ ...data })
        }
        //麒麟linux系统vue应用向主程序发送信息
        try{
            if (window.qt) {
                console.log('向主程序发送了', data)
                window.sendObject.receiveMessage(JSON.stringify({ ...data }));
            }
        }catch(e){
            alert(''+e)
        }

        watch(restDataMain, (newRst, oldRst) => {
            loadingInstance.close()
            console.log('关闭加载', loadingInstance)
            if (newRst.webInfo && newRst.webInfo.requestId == randomStr) {
                localStorage.setItem('auth_token',newRst.webInfo.token)
                console.log('接收到后端消息', newRst)
               
                if (newRst.response.code == 0) {
                    resolve(newRst.response)
                } else {
                    ElMessage({
                        message: newRst.response.message,
                        type: 'error',
                    })
                    reject(newRst.response)
                }
            }
        })
        
    })
}


export default service
